package cn.xianyang.user.service.impl;

import cn.xianyang.basic.constants.BaseConstant;
import cn.xianyang.basic.dto.EmailRegisterDto;
import cn.xianyang.basic.dto.RegisterDto;
import cn.xianyang.basic.exception.BusinessException;
import cn.xianyang.basic.util.MD5Utils;
import cn.xianyang.basic.util.StrUtils;
import cn.xianyang.user.domain.Logininfo;
import cn.xianyang.user.domain.User;
import cn.xianyang.user.mapper.LogininfoMapper;
import cn.xianyang.user.mapper.UserMapper;
import cn.xianyang.user.service.IUserService;
import cn.xianyang.basic.service.impl.BaseServiceImpl;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xianyang
 * @since 2022-06-16
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     * @param dto
     */
    @Override
    public void phoneRegister(RegisterDto dto) {
        //获取传过来手机号
        String phone = dto.getPhone();
        String smsCode = dto.getSmsCode();
        String password = dto.getPassword();
        String passwordRepeat = dto.getPasswordRepeat();
        //为空检验
        if (StringUtils.isEmpty(smsCode) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("不好意思,您输入的参数异常");
        }
        //密码是否一致
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致,请仔细填写");
        }
        //短信验证码判断,通过手机号去拿redis  ，注入redis
        String key = BaseConstant.RegisterConstants.REGISTER_SMS_PREFIX + phone;
        Object smsCodeTmp = redisTemplate.opsForValue().get(key);
        //拿不到，就重新获取 验证码
        if (smsCodeTmp == null){
            throw new BusinessException("不好意思,验证码已过期,请重新获取");
        }
        //拿到了就正常执行流程。判断是否一致 验证码   equalsIgnoreCase 不区分大小写
        if (!smsCode.equalsIgnoreCase(smsCodeTmp.toString().split(":")[0])){
            //如果不一致请核对
            throw new BusinessException("请核对，并且输入正确的验证码");
        }
        //保存数据user+loginfo 一致..把dto转为user对象
        User user = dto2User(dto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    /**
     * 用户邮箱注册
     * @param dto
     */
    @Override
    public void emailRegister(EmailRegisterDto dto) {
        String email = dto.getEmail();
        String mailCodeValue = dto.getMailCodeValue();
        String password = dto.getPassword();
        String passwordRepeat = dto.getPasswordRepeat();
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(mailCodeValue) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("参数不能为空");
        }
        //判断两次密码是否相等
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("密码不一致，请重新输入");
        }
        //判断邮箱验证是否正确
        String emailCodeValue = (String)redisTemplate.opsForValue().get(BaseConstant.RegisterConstants.REGISTER_SMS_PREFIX + email);
        if (emailCodeValue == null){
            throw new BusinessException("邮箱验证码过期，请重新获取");
        }
        if (!emailCodeValue.split(":")[0].equalsIgnoreCase(mailCodeValue)){
            throw new BusinessException("邮箱验证码错误，请重新输入");
        }
        //判断邮箱是否注册
        User userTemp = userMapper.loadByEmail(email);
        if(userTemp != null){
            throw new BusinessException("该用户已存在,请直接登录!");
        }
        //5.保存数据 user表和logininfo表都要保存
        //保存user对象
        User user = initUser(dto);
        insert(user);


    }

    private void insert(User user) {
        //设置用户的盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //设置用户的加密密码
        user.setPassword(MD5Utils.encrypByMd5(user.getPassword() + salt));
        //根据user对象获取logininfo对象
        Logininfo logininfo = user2Logininfo(user);
        //设置类型 true 1 用户
        logininfo.setType(1);
        //新增日志对象
        logininfoMapper.save(logininfo);
        //设置user对象的loginid
        user.setLogininfoId(logininfo.getId());
        //保存user对象
        userMapper.save(user);
    }


    /**
     * EmailRegisterDto初始化user对象
     * @param dto
     * @return
     */
    private User initUser(EmailRegisterDto dto) {
        User user = new User();
        user.setUsername(dto.getEmail());
        user.setEmail(dto.getEmail());
        user.setPassword(dto.getPassword());
        return user;
    }


    @Override
    public User loadByLogininfoId(Long id) {
        return userMapper.loadByLogininfoId(id);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //同名原则拷贝\\user 原 ，logininfo 目标
        BeanUtils.copyProperties(user,logininfo,"id");
        //一定要手动设置Type  ，前端用户注册1
        logininfo.setType(1);
        return logininfo;
    }
    private User dto2User(RegisterDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        //设置盐值加密
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        //原密码
        user.setSalt(salt);
        //加密之后比对的密码
        user.setPassword(md5Pwd);
        return user;
    }

    /**
     * 级联操作logininfo
     * @param user
     */
    @Override
    public void update(User user){
        super.update(user);
    }

    @Override
    public void removeById(Long id){
        super.removeById(id);
    }


}
